#!/usr/bin/python3
# 文件名：server4multiClient.py

# 导入 socket、sys 模块
import socket
import sys

# 创建 socket 对象
serversocket = socket.socket(
    socket.AF_INET, socket.SOCK_STREAM)

# 获取本地主机名
host = socket.gethostname()

port = 12346
#print(host,port)
# 绑定端口号
serversocket.bind(('127.0.0.1', port))

# 设置最大连接数，超过后排队
serversocket.listen(200)
#不堵塞
serversocket.setblocking(False)
clientsocket_cache = {}

while True:
    # 建立客户端连接
    for addr, soc in clientsocket_cache.items():
        try:
            from_client = soc.recv(100)
            if len(from_client)>0:
                print('I get msg:',from_client)
            msg = 'I get msg:  '+from_client.decode('utf-8') + "\r\n"
            soc.send(msg.encode('utf-8'))
        except Exception:
            pass
    # 防止异常
    try:
        clientsocket, addr = serversocket.accept()
        clientsocket_cache[addr] = clientsocket
    except Exception:
        pass
clientsocket.close()
serversocket.close()